import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tiktokadult/alert_business/video/share_video_dialog.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_model/video_model.dart';
import 'package:tiktokadult/hj_page/cartoon_business/cartoon_recommend_page.dart';
import 'package:tiktokadult/hj_page/cartoon_business/novel_header.dart';
import 'package:tiktokadult/hj_page/comment/comment_views.dart';
import 'package:tiktokadult/hj_utils/screen.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/tools_base/banner/ads_grid_view_widget.dart';
import 'package:tiktokadult/tools_base/widget/keep_alive_widget.dart';

import '../../tools_base/loading/l_error_widget.dart';
import '../../tools_base/loading/loading_center_widget.dart';
import 'novel_detail_logic.dart';
import 'widget/acg_source_manager.dart';

//小说详情页 -
class NovelDetailPage extends StatelessWidget {
  static const routeName = '/acg/storydetail';
  static const routeTitle = '小说详情首页';
  late String? id;
  late String tag;

  NovelDetailPage({super.key}) {
    id = Get.arguments;
    assert(id != null, 'StoryDetailPage id 不能为空');
    tag = id! + '_' + DateTime.now().millisecond.toString();
    Get.put<NovelDetailLogic>(NovelDetailLogic(id!), tag: tag);
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<NovelDetailLogic>(
      tag: tag,
      builder: (_) => Scaffold(
        body: () {
          if (_.model == null) return LoadingCenterWidget();
          if (_.model?.id == null) return CErrorWidget();
          return ChangeNotifierProvider<ACGSourceManager>.value(
            value: _.manager,
            child: _buildContent(_),
          );
        }(),
      ),
    );
  }

  _buildContent(NovelDetailLogic _) {
    return Stack(
      children: [
        ExtendedNestedScrollView(
          controller: _.scrollCtr,
          onlyOneScrollInBody: true,
          headerSliverBuilder: (context, innerBoxIsScrolled) {
            return [
              SliverToBoxAdapter(
                child: _buildNovelHeader(_),
              )
            ];
          },
          body: TabBarView(
            controller: _.tabCtr,
            children: [
              CartoonRecommendPage(
                showHeader: true,
                mediaId: _.manager.mediaInfo?.id,
                mainLogic: _,
                recommengTitle: '看了又看',
              ).keepAlive,
              CommentView(
                _.manager.mediaInfo?.id ?? '',
                objType: "video",
                totalCallback: (value) {
                  _.totalCtCount.value = value;
                },
              ).keepAlive,
            ],
          ),
        ),
        Positioned(
          top: 0,
          left: 0,
          right: 0,
          child: _buildTopHeader(_),
        )
      ],
    );
  }

  _buildTopHeader(NovelDetailLogic _) {
    return GetBuilder<NovelDetailLogic>(
      id: 'header',
      tag: tag,
      builder: (_) {
        return Container(
          padding: EdgeInsets.only(left: 16, right: 16, top: screen.paddingTop),
          height: 44 + screen.paddingTop,
          color: !_.showHeader ? Color(0xff0E141E) : Colors.transparent,
          child: Row(
            children: [
              InkWell(
                onTap: () => Get.back(),
                child: Icon(
                  Icons.arrow_back_ios_new,
                  weight: 24,
                  color: Colors.white,
                ),
              ),
              40.sizeBoxW,
              Spacer(),
              Text(
                !_.showHeader ? '${_.model?.title ?? ''}' : '',
                style: textStyle(16, Colors.white, FontWeight.w500),
              ),
              Spacer(),
              InkWell(
                onTap: () {
                  Get.dialog(
                    ShareVideoDialog(
                      isCoverV: true,
                      videoModel: VideoModel()
                        ..id = _.model?.id
                        ..cover = _.model?.coverH,
                    ),
                  );
                },
                child: Image.asset('acg_share.png'.acgImgPath, width: 24),
              ),
            ],
          ),
        );
      },
    );
  }

  _buildNovelHeader(NovelDetailLogic _) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        NovelHeader(manager: _.manager),
        12.sizeBoxH,
        Consumer<ACGSourceManager>(builder: (context, manager, child) {
          bool liked = manager.mediaInfo?.mediaStatus?.hasLiked ?? false;
          bool collected = manager.mediaInfo?.mediaStatus?.hasAddBookshelf ?? false;
          return Padding(
            padding: EdgeInsets.symmetric(horizontal: 50),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                _buildStatusItem(
                  manager.mediaInfo?.countBrowse?.humanizeFormat ?? '',
                  'browse.png'.commonImgPath,
                ),
                _buildStatusItem(
                  manager.mediaInfo?.countLike?.humanizeFormat ?? '',
                  liked ? 'acg_like_sel.png'.acgImgPath : 'acg_like_nor.png'.acgImgPath,
                  action: () => manager.onLikeAction(),
                ),
                _buildStatusItem(
                  '收藏',
                  collected ? 'collect_red.png'.commonImgPath : 'collect_white.png'.commonImgPath,
                  action: () => manager.onCollectAction(),
                )
              ],
            ),
          );
        }),
        //广告
        AdsGridViewWidget(
          2,
          isBigStyle: true,
          padding: EdgeInsets.symmetric(vertical: 18),
        ),
        //简介
        18.sizeBoxH,
        Row(
          children: [
            Spacer(),
            TabBar(
              tabAlignment: TabAlignment.center,
              controller: _.tabCtr,
              tabs: List.generate(
                  _.tabs.length,
                  (index) => Padding(
                        padding: const EdgeInsets.only(top: 12, bottom: 4),
                        child: FittedBox(
                          child: Text(_.tabs[index]),
                        ),
                      )),
              isScrollable: false,
              labelColor: Colors.white,
              labelStyle: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
              unselectedLabelColor: Colors.white.withOpacity(0.6),
              unselectedLabelStyle: const TextStyle(fontSize: 14, fontWeight: FontWeight.w400),
              indicator: BoxDecoration(),
            ),
            Spacer(),
          ],
        ),
      ],
    );
  }

  _buildStatusItem(String title, String img, {Function? action}) {
    return InkWell(
      onTap: () => action?.call(),
      child: Row(
        children: [
          Image.asset(img, width: 20),
          4.sizeBoxW,
          Text(
            title,
            style: textStyle(12, Colors.white.withOpacity(.9), FontWeight.w400),
          )
        ],
      ),
    );
  }
}
